<template>
  <n-modal v-model:show="showModal" preset="dialog" :show-icon="false">
    <n-card v-if="editType==='edit' || editType==='add'" class="w-600px">
      <h1 class="text-center text-4xl mb-4">{{ title }}</h1>
      <n-form ref="formRef" :model="formValue" :rules="rules" :label-width="100"
              label-placement="left">
        <n-grid x-gap="12">
          <n-gi :span="24">
            <n-form-item label="菜单名称" path="name">
              <n-input v-model:value="formValue.name" @keydown.enter.prevent
                       placeholder="请输入菜单名称" clearable>
              </n-input>
            </n-form-item>
          </n-gi>
          <n-gi :span="24">
            <n-form-item label="父级菜单" path="parent">
              <n-cascader
                  v-model:value="formValue['parent']"
                  placeholder="请选择"
                  :options="parentoptions"
                  remote
                  :show-path="false"
                  clearable
                  :on-load="handleLoad"
              />
            </n-form-item>
          </n-gi>
          <n-gi :span="24">
            <n-form-item label="菜单排序" path="paixu">
              <n-input-number v-model:value="formValue['paixu']" placeholder="请输入排序" clearable/>
            </n-form-item>
          </n-gi>
          <n-gi :span="24">
            <n-form-item label="菜单分类" path="fenlei">
              <n-radio-group v-model:value="formValue.fenlei" name="radiogroup">
                <n-space>
                  <n-radio value="1">
                    目录
                  </n-radio>
                  <n-radio value="2">
                    外联
                  </n-radio>
                </n-space>
              </n-radio-group>
            </n-form-item>
          </n-gi>
          <n-gi :span="24" v-if="formValue.fenlei==='1'">
            <n-form-item label="路由地址" path="route">
              <n-input v-model:value="formValue.route" @keydown.enter.prevent
                       placeholder="请输入路由地址" clearable>
              </n-input>
            </n-form-item>
          </n-gi>
          <n-gi :span="24" v-if="formValue.fenlei==='1'">
            <n-form-item label="组件路径" path="path">
              <n-input v-model:value="formValue.path" @keydown.enter.prevent
                       placeholder="请输入组件路径" clearable>
              </n-input>
            </n-form-item>
          </n-gi>
          <n-gi :span="24" v-if="formValue.fenlei==='1'">
            <n-form-item label="组件name" path="menukey">
              <n-input v-model:value="formValue.menukey" @keydown.enter.prevent
                       placeholder="请输入组件name" clearable>
              </n-input>
            </n-form-item>
          </n-gi>
          <n-gi :span="24">
            <n-form-item label="外链url" path="url" v-if="formValue.fenlei==='2'">
              <n-input v-model:value="formValue.url" @keydown.enter.prevent
                       placeholder="请输入外链url" clearable>
              </n-input>
            </n-form-item>
          </n-gi>
          <n-gi :span="24">
            <n-form-item label="是否缓存" path="cache">
              <n-radio-group v-model:value="formValue.cache" name="radiogroup">
                <n-space>
                  <n-radio value="1">
                    是
                  </n-radio>
                  <n-radio value="2">
                    否
                  </n-radio>
                </n-space>
              </n-radio-group>
            </n-form-item>
          </n-gi>
          <n-gi :span="24">
            <n-form-item label="状态" path="status">
              <n-radio-group v-model:value="formValue.status" name="radiogroup">
                <n-space>
                  <n-radio value="1">
                    启用
                  </n-radio>
                  <n-radio value="2">
                    停用
                  </n-radio>
                </n-space>
              </n-radio-group>
            </n-form-item>
          </n-gi>
          <n-gi :span="24">
            <n-form-item label="描述" path="desc">
              <n-input v-model:value="formValue.desc" @keydown.enter.prevent
                       type="textarea"
                       placeholder="请输入描述" clearable>
              </n-input>
            </n-form-item>
          </n-gi>
        </n-grid>
      </n-form>
      <template #action>
        <div class="w-full h-10 flex justify-end items-center">
          <n-button @click="doClose">取消</n-button>
          <n-button @click="handleOK" type="primary">{{ formValue.id ? "编辑" : "创建" }}</n-button>
        </div>
      </template>
    </n-card>
    <n-card v-if="editType==='view'">
      <h1 class="text-center text-4xl mb-4">{{ title }}</h1>
      <descriptions :infoList="_lanmulist"></descriptions>
      <template #action>
        <div class="w-full h-10 flex justify-end items-center">
          <n-button @click="clickEdit" type="primary">编辑</n-button>
          <n-button @click="doClose">关闭</n-button>
        </div>
      </template>
    </n-card>
    <n-card v-if="editType==='success'">
      <n-result status="success" title="成功" :description="formValue.id?'编辑成功':'创建成功'">
      </n-result>
      <template #action>
        <div class="w-full h-10 flex justify-end items-center">
          <n-button @click="doClose">关闭</n-button>
        </div>
      </template>
    </n-card>
    <n-card v-if="editType==='error'">
      <n-result status="error" title="错误">
        <template>
          <p>{{ errortext }}</p>
        </template>
      </n-result>
      <template #action>
        <div class="w-full h-10 flex justify-end items-center">
          <n-button @click="getreturn" type="primary">返回</n-button>
          <n-button @click="doClose">关闭</n-button>
        </div>
      </template>
    </n-card>
  </n-modal>
</template>

<script setup name="Edit">
import {useRoute, useRouter} from "vue-router";
import http from "@/request/request"
import guilingfunc from "../../../../util/guiling";

const router = useRouter()
const route = useRoute()
const formRef = ref(null)   // 表单组件
const showModal = ref(false)    // 模态框的显示
const title = ref("")         // 标题
const loading = ref(false)    // 加载状态
const editType = ref("add")   // 类型，编辑。新建、查看
const formValue = ref({})   // 表单数据

const rules = ref({
  name: [{required: true, message: "请输入菜单名称", trigger: ["input", "change", "blur"]}, {
    max: 50,
    min: 2,
    message: "请输入2-50为的字符",
    trigger: ["input", "change", "blur"]
  },],
  parent: [],
  paixu: [{type: "number", required: true, message: "请选择排序", trigger: ["input", "change", "blur"]}],
  fenlei: [{required: true, message: "请选择分类", trigger: ["input", "change", "blur"]}],
  route: [{required: true, message: "请输入路由地址", trigger: ["input", "change", "blur"]}, {
    max: 200, min: 2, message: "请输入2-200字符", trigger: ["input", "change", "blur"]
  }],
  path: [{required: true, message: "请输入组件路径", trigger: ["input", "change", "blur"]}, {
    max: 200, min: 2, message: "请输入2-200字符", trigger: ["input", "change", "blur"]
  }],
  menukey: [{required: true, message: "请输入组件name", trigger: ["input", "change", "blur"]}, {
    max: 200, min: 2, message: "请输入2-200字符", trigger: ["input", "change", "blur"]
  }],
  cache: [{required: true, message: "请选择是否缓存", trigger: ["input", "change", "blur"]}],
  status: [{required: true, message: "请选择状态", trigger: ["input", "change", "blur"]}],
  desc: [{
    max: 2000,
    message: "最多2000字符",
  }],
  url: [{required: true, message: "请输入外链URL", trigger: ["input", "change", "blur"]}, {
    validator: (rule, value) => {
      const regx = /(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/;
      if (!value) {
        return true
      } else if (!regx.test(value)) {
        return new Error('请输入合法的URL')
      } else {
        return true
      }
    }, trigger: ["input", "change", "blur"]
  }],
})   // 表单的校验数据
const errortext = ref("")   // 错误信息

const emit = defineEmits(["shuaxin"])
// 弹窗初始化
const init = (type, item = null) => {
  editType.value = type
  switch (type) {
    case "add":
      title.value = "新建"
      break;
    case "edit":
      title.value = "编辑"
      break;
    case "view":
      title.value = "详情"
      break;
  }
  if (item) {
    formValue.value = item
  }
  getmenulist()
  showModal.value = true
}
// 关闭弹窗
const doClose = () => {
  showModal.value = false
  emit("shuaxin")
  reset()
}
// 重置弹窗
const reset = () => {
  console.log("重置函数执行")
  formValue.value = guilingfunc(formValue.value)
  editType.value = ""
  title.value = ""
  console.log(formValue.value, "重置结果")
}
// 点击确定
const handleOK = () => {
  formRef.value?.validate((errors) => {
    if (!errors) {
      const data = {...formValue.value}
      if (formValue.value.id) {
        updatefunc(data)
      } else {
        createfunc(data)
      }
    } else {
      return false
    }
  })
}

// 创建的处理函数
const createfunc = (data) => {
  http.menuadd(data).then(res => {
    if (res && res.data.code === 0) {
      getsuccess()
    } else {
      getfaild()
    }
  }).catch(() => {
    getfaild()
  })
}
// 编辑的处理函数
const updatefunc = (data) => {
  http.menuupdate(data, formValue.value.id).then(res => {
    if (res && res.data.code === 0) {
      getsuccess()
    } else {
      getfaild(res.data)
    }
  }).catch(() => {
    getfaild()
  })
}

// 表单配置
const formList = ref([
  {
    label: "菜单名称",
    key: "name",
    type: "input",
    rules: [{required: true, message: "请输入菜单名称", trigger: ["input", "change", "blur"]}, {
      max: 50,
      min: 2,
      message: "请输入2-50为的字符",
      trigger: ["input", "change", "blur"]
    },]
  },
  {
    label: "父级菜单",
    slot: "parent",    // 这个使用插槽形式
    key: "parent",
    type: "select",
    rules: [{required: true, message: "请选择父级菜单", trigger: ["input", "change", "blur"]}]
  },
  {
    label: "菜单排序",
    slot: "paixu",    // 这个使用插槽形式
    key: "paixu",
    type: "number",
    rules: [{type: "number", required: true, message: "请选择排序", trigger: ["input", "change", "blur"]}]
  },
  {
    label: "分类", // 这个使用插槽形式
    key: "fenlei",
    type: "radio",
    options: [
      {label: "目录", value: "1"},
      {label: "外联", value: "2"},
    ],
    rules: [{required: true, message: "请选择分类", trigger: ["input", "change", "blur"]}]
  },
  {
    label: "路由地址",
    key: "route",
    type: "input",
    rules: [{required: true, message: "请输入路由地址", trigger: ["input", "change", "blur"]}, {
      max: 200, min: 2, message: "请输入2-200字符", trigger: ["input", "change", "blur"]
    }]
  },
  {
    label: "组件路径",
    key: "path",
    type: "input",
    rules: [{required: true, message: "请输入组件路径", trigger: ["input", "change", "blur"]}, {
      max: 200, min: 2, message: "请输入2-200字符", trigger: ["input", "change", "blur"]
    }]
  },
  {
    label: "是否缓存",
    key: "cache",
    type: "radio",
    options: [
      {label: "是", value: "1"},
      {label: "否", value: "2"},
    ],
    rules: [{required: true, message: "请选择是否缓存", trigger: ["input", "change", "blur"]}]
  },
  {
    label: "状态",
    key: "status",
    type: "radio",
    options: [
      {label: "启用", value: "1"},
      {label: "停用", value: "2"},
    ],
    rules: [{required: true, message: "请选择状态", trigger: ["input", "change", "blur"]}]
  },
  {
    label: "描述",
    key: "desc",
    type: "textarea",
    rules: [{
      max: 2000,
      message: "最多2000字符",
    }]
  },
])

// 交互成功
const getsuccess = () => {
  editType.value = "success"
  setTimeout(() => {
    doClose()
  }, 500)
}
// 交互失败
const getfaild = (jieguo) => {
  editType.value = "error"
  errortext.value = jieguo.toString()
}


// 显示相关的配置
const lanmulist = ref([
  {label: "菜单名称", key: "name"},
  {label: "父级菜单", key: "parent"},
  {label: "菜单排序", key: "paixu"},
  {
    label: "分类", key: "fenlei", render: (val) => {
      return +val === 1 ? "目录" : "外链"
    }
  },
  {label: "路由地址", key: "route"},
  {label: "组件路径", key: "path"},
  {label: "组件name", key: "menukey"},
  {
    label: "是否缓存", key: "cache", render: (val) => {
      return +val === 1 ? "是" : "否"
    }
  },
  {
    label: "状态", key: "status", render: (val) => {
      return +val === 1 ? "启用" : "停用"
    }
  },
  {
    label: "创建时间", key: "createdTime", render: (val) => {
      return val ? new Date(parseInt(val)).toLocaleString("zh", {
        year: 'numeric',
        month: 'numeric',
        day: 'numeric',
        hour12: false,
        hour: 'numeric',
        minute: 'numeric',
        second: 'numeric'
      }) : ""
    }
  },
  {
    label: "更新时间", key: "changeTime", render: (val) => {
      return val ? new Date(parseInt(val)).toLocaleString("zh", {
        year: 'numeric',
        month: 'numeric',
        day: 'numeric',
        hour12: false,
        hour: 'numeric',
        minute: 'numeric',
        second: 'numeric'
      }) : ""
    }
  },
  {label: "描述", key: "desc"},
])
const _lanmulist = computed(() => {
  return lanmulist.value.map(item => {
    return {...item, value: item.render ? item.render(formValue.value[item.key]) : formValue.value[item.key]}
  })
})
// 点击编辑按钮
const clickEdit = () => {
  editType.value = "edit"
  title.value = "编辑"
}
// 点击返回
const getreturn = () => {
  if (formValue.value.id) {
    editType.value = "edit"
    title.value = "编辑"
  } else {
    editType.value = "add"
    title.value = "创建"
  }
  errortext.value = ""
}


// 父级菜单
const parentoptions = ref([])

const handleLoad = (option) => {
  console.log("触发handleLoad", option)
  return new Promise((resolve) => {
    const config = {
      parent: option.value,
    }
    http.menufilter(config).then(res => {
      if (res.data.code === 0) {
        if (res.data.items.length === 0) {
          option.isLeaf = true
        } else {
          option.children = res.data.items.map(item => {
            return {label: item.name, value: item.id, isLeaf: false,}
          })
        }
        resolve()
        console.log(222)
      }
    })
  })
}


// 获取顶级菜单
const getmenulist = () => {
  http.menufilter().then(res => {
    if (res.data.code === 0) {
      parentoptions.value = res.data.items.map(item => {
        return {label: item.name, value: item.id, isLeaf: false,}
      })
    }
  })
}

defineExpose({init, doClose, reset})
</script>

<style scoped>

</style>
